import React, { useState, useEffect } from 'react'
import { Plus, Search, Edit, Trash2, Play, Pause, Filter } from 'lucide-react'

function RouteManagement() {
  const [routes, setRoutes] = useState([])
  const [searchTerm, setSearchTerm] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingRoute, setEditingRoute] = useState(null)
  const [formData, setFormData] = useState({
    name: '',
    path: '',
    target: '',
    method: 'ALL',
    rateLimit: 100,
    timeout: 30
  })

  useEffect(() => {
    loadRoutes()
  }, [])

  const loadRoutes = async () => {
    setIsLoading(true)
    try {
      // 这里应该调用后端API获取路由规则
      // const response = await fetch('/api/routes')
      // const data = await response.json()
      // setRoutes(data)
      
      // 模拟数据
      setTimeout(() => {
        setRoutes([
          { 
            id: 1, 
            name: 'API Gateway', 
            path: '/api/*', 
            target: 'http://localhost:3001', 
            method: 'ALL',
            status: 'active',
            createdAt: '2024-01-15',
            rateLimit: 1000,
            timeout: 30
          },
          { 
            id: 2, 
            name: 'User Service', 
            path: '/api/users/*', 
            target: 'http://localhost:3002', 
            method: 'ALL',
            status: 'active',
            createdAt: '2024-01-20',
            rateLimit: 500,
            timeout: 10
          },
          { 
            id: 3, 
            name: 'Product Service', 
            path: '/api/products/*', 
            target: 'http://localhost:3003', 
            method: 'GET,POST',
            status: 'inactive',
            createdAt: '2024-01-25',
            rateLimit: 200,
            timeout: 15
          }
        ])
        setIsLoading(false)
      }, 1000)
    } catch (error) {
      console.error('加载路由规则失败:', error)
      setIsLoading(false)
    }
  }

  const toggleRouteStatus = async (routeId) => {
    try {
      // 这里应该调用后端API切换路由状态
      // await fetch(`/api/routes/${routeId}/toggle`, { method: 'POST' })
      
      setRoutes(routes.map(route =>
        route.id === routeId 
          ? { ...route, status: route.status === 'active' ? 'inactive' : 'active' }
          : route
      ))
    } catch (error) {
      console.error('切换路由状态失败:', error)
    }
  }

  const handleEditRoute = (route) => {
    setEditingRoute(route)
    setFormData({
      name: route.name,
      path: route.path,
      target: route.target,
      method: route.method,
      rateLimit: route.rateLimit,
      timeout: route.timeout
    })
  }

  const handleSaveRoute = async () => {
    try {
      if (editingRoute) {
        // 更新现有路由
        setRoutes(routes.map(route =>
          route.id === editingRoute.id
            ? { ...route, ...formData }
            : route
        ))
      } else {
        // 添加新路由
        const newRoute = {
          id: Math.max(...routes.map(r => r.id), 0) + 1,
          ...formData,
          status: 'active',
          createdAt: new Date().toISOString().split('T')[0]
        }
        setRoutes([...routes, newRoute])
      }
      
      setShowCreateModal(false)
      setEditingRoute(null)
      setFormData({
        name: '',
        path: '',
        target: '',
        method: 'ALL',
        rateLimit: 100,
        timeout: 30
      })
    } catch (error) {
      console.error('保存路由失败:', error)
    }
  }

  const handleDeleteRoute = async (routeId) => {
    if (confirm('确定要删除这个路由规则吗？')) {
      try {
        setRoutes(routes.filter(route => route.id !== routeId))
      } catch (error) {
        console.error('删除路由失败:', error)
      }
    }
  }

  const handleFormChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const filteredRoutes = routes.filter(route =>
    route.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    route.path.toLowerCase().includes(searchTerm.toLowerCase()) ||
    route.target.toLowerCase().includes(searchTerm.toLowerCase())
  )

  const getStatusColor = (status) => {
    return status === 'active' ? 'bg-green-500' : 'bg-red-500'
  }

  const getMethodColor = (method) => {
    if (method === 'ALL') return 'bg-purple-500'
    if (method.includes('GET')) return 'bg-green-500'
    if (method.includes('POST')) return 'bg-blue-500'
    if (method.includes('PUT')) return 'bg-yellow-500'
    if (method.includes('DELETE')) return 'bg-red-500'
    return 'bg-gray-500'
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white mb-2">路由管理</h1>
            <p className="text-blue-200">管理网关路由规则和转发配置</p>
          </div>
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors duration-200"
          >
            <Plus className="h-4 w-4 mr-2" />
            添加路由
          </button>
        </div>
      </div>

      {/* Search and Filter */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
        <div className="flex items-center space-x-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-blue-300 h-4 w-4" />
            <input
              type="text"
              placeholder="搜索路由名称、路径或目标地址..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
            />
          </div>
          <button className="flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors duration-200">
            <Filter className="h-4 w-4 mr-2" />
            筛选
          </button>
        </div>
      </div>

      {/* Routes Table */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl border border-white/20 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/10">
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">路由信息</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">目标服务</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">方法</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">状态</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-200 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {filteredRoutes.map((route) => (
                <tr key={route.id} className="hover:bg-white/5 transition-colors duration-200">
                  <td className="px-6 py-4">
                    <div>
                      <div className="text-sm font-medium text-white">{route.name}</div>
                      <div className="text-sm text-blue-300">{route.path}</div>
                      <div className="text-xs text-blue-400 mt-1">
                        限流: {route.rateLimit}/s • 超时: {route.timeout}s
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="text-sm text-blue-300 break-all">{route.target}</div>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium text-white ${getMethodColor(route.method)}`}>
                      {route.method}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center space-x-2">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium text-white ${getStatusColor(route.status)}`}>
                        {route.status === 'active' ? '启用' : '禁用'}
                      </span>
                      <button
                        onClick={() => toggleRouteStatus(route.id)}
                        className={`p-1 rounded transition-colors duration-200 ${
                          route.status === 'active' 
                            ? 'text-red-400 hover:text-red-300' 
                            : 'text-green-400 hover:text-green-300'
                        }`}
                      >
                        {route.status === 'active' ? <Pause className="h-3 w-3" /> : <Play className="h-3 w-3" />}
                      </button>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center space-x-2">
                      <button 
                        onClick={() => handleEditRoute(route)}
                        className="text-blue-400 hover:text-blue-300 transition-colors duration-200"
                      >
                        <Edit className="h-4 w-4" />
                      </button>
                      <button 
                        onClick={() => handleDeleteRoute(route.id)}
                        className="text-red-400 hover:text-red-300 transition-colors duration-200"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        {isLoading && (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto"></div>
            <p className="text-blue-300 mt-2">加载中...</p>
          </div>
        )}
        
        {!isLoading && filteredRoutes.length === 0 && (
          <div className="p-8 text-center">
            <p className="text-blue-300">未找到匹配的路由规则</p>
          </div>
        )}
      </div>

      {/* Create/Edit Route Modal */}
      {(showCreateModal || editingRoute) && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-md border border-white/20">
            <h3 className="text-xl font-bold text-white mb-4">
              {editingRoute ? '编辑路由规则' : '添加路由规则'}
            </h3>
            
            <div className="space-y-4">
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">路由名称</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => handleFormChange('name', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="请输入路由名称"
                />
              </div>
              
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">路径匹配</label>
                <input
                  type="text"
                  value={formData.path}
                  onChange={(e) => handleFormChange('path', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="例如: /api/*"
                />
              </div>
              
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">目标服务</label>
                <input
                  type="text"
                  value={formData.target}
                  onChange={(e) => handleFormChange('target', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="例如: http://localhost:3001"
                />
              </div>
              
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">HTTP方法</label>
                <select 
                  value={formData.method}
                  onChange={(e) => handleFormChange('method', e.target.value)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                >
                  <option value="ALL">全部方法</option>
                  <option value="GET">GET</option>
                  <option value="POST">POST</option>
                  <option value="PUT">PUT</option>
                  <option value="DELETE">DELETE</option>
                </select>
              </div>

              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">请求频率限制(次/秒)</label>
                <input
                  type="number"
                  value={formData.rateLimit}
                  onChange={(e) => handleFormChange('rateLimit', parseInt(e.target.value) || 0)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="请输入频率限制"
                />
              </div>

              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">超时时间(秒)</label>
                <input
                  type="number"
                  step="0.1"
                  value={formData.timeout}
                  onChange={(e) => handleFormChange('timeout', parseFloat(e.target.value) || 0)}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="请输入超时时间"
                />
              </div>
            </div>
            
            <div className="flex items-center justify-end space-x-3 mt-6">
              <button
                onClick={() => {
                  setShowCreateModal(false)
                  setEditingRoute(null)
                  setFormData({
                    name: '',
                    path: '',
                    target: '',
                    method: 'ALL',
                    rateLimit: 100,
                    timeout: 30
                  })
                }}
                className="px-4 py-2 text-blue-300 hover:text-white transition-colors duration-200"
              >
                取消
              </button>
              <button 
                onClick={handleSaveRoute}
                className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors duration-200"
              >
                {editingRoute ? '保存修改' : '添加路由'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default RouteManagement